package top.tupobi.flutterdemo.plugins

import android.app.Activity
import android.widget.Toast
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class NativePluginForFlutter : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware {

    private lateinit var mRootActivity: Activity
    private lateinit var mMethodChannel: MethodChannel

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        val methodChannelName = "top.tupobi.demo/channel_connection"
        mMethodChannel = MethodChannel(binding.binaryMessenger, methodChannelName)
        mMethodChannel.setMethodCallHandler(this)
        println("native 初始化mMethodChannel")
        mMethodChannel.invokeMethod("flutterToast", mapOf("message" to "messageFromNative"))
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "nativeToast" -> {
                val message = call.argument<String>("message")
                Toast.makeText(mRootActivity, "toast from native, message = $message", Toast.LENGTH_LONG).show()
                mMethodChannel.invokeMethod("flutterFunction", mapOf("message" to "messageFromNative"))
            }
        }
    }

    override fun onDetachedFromActivity() {
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        this.mRootActivity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {
    }
}